package com.tbit.uqbike.quartz;

import com.tbit.uqbike.constant.OperaPswConstant;
import com.tbit.uqbike.constant.RechargeConstant;
import com.tbit.uqbike.object.pojo.*;
import com.tbit.uqbike.object.pojo.dto.CommonDTO;
import com.tbit.uqbike.object.pojo.statistics.*;
import com.tbit.uqbike.object.value.UserRcDetail;
import com.tbit.uqbike.webmanager.dao.core.*;
import com.tbit.uqbike.webmanager.dao.capital.MoneyOpeLogDao;
import com.tbit.uqbike.webmanager.dao.log.RideRefundLogDao;
import com.tbit.uqbike.webmanager.dao.log.UserMealLogDao;
import com.tbit.uqbike.webmanager.dao.log.UserRefundLogDao;
import com.tbit.uqbike.webmanager.dao.stat.ReconciliationDao;
import com.tbit.uqbike.webmanager.dao.stat.RideOrderDayStaDao;
import com.tbit.uqbike.webmanager.util.StringUtil;
import com.tbit.utils.CSVUtil;
import com.tbit.utils.DateTimeUtil;
import com.tbit.utils.DateTimes;
import com.tbit.utils.NullUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author HZW
 * @ClassName ReconciliationQuartz
 * @Description 对账数据预统计定时任务
 * @date 2022/3/28 10:51
 * @Version 1.0
 */
@Component
@Slf4j
public class ReconciliationQuartz {

    @Autowired
    private AccountDao accountDao;
    @Autowired
    private ReconciliationDao reconciliationDao;
    @Autowired
    private RideOrderDayStaDao rideOrderDayStaDao;
    @Autowired
    private StatDataDao statDataDao;
    @Autowired
    private UserMealLogDao userMealLogDao;
    @Autowired
    private WeixinDepositLogDao weixinDepositLogDao;
    @Autowired
    private MoneyOpeLogDao moneyOpeLogDao;
    @Autowired
    private RechargeDao rechargeDao;
    @Autowired
    private RideLogDao rideLogDao;
    @Autowired
    private RideRefundLogDao rideRefundLogDao;
    @Autowired
    private RideCardDao rideCardDao;
    @Autowired
    private VipCardDao vipCardDao;
    @Autowired
    private MemberFeeDao memberFeeDao;
    @Autowired
    private CouponMealDao couponMealDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AccountUserDao accountUserDao;
    @Autowired
    private UserRefundLogDao userRefundLogDao;


    public void total(String accountIds, String startDate, String endDate) throws ParseException {
        List<Integer> detects = StringUtil.getIntegerList(accountIds);
        String brandId = "";
        if (!NullUtils.isEmpty(detects)) {
            brandId = accountDao.getAgentId(detects.get(0)).getParentId().toString();
        }

        reAccountOrder(accountIds, startDate, endDate);
        reBrandOrder(brandId, startDate, endDate);
        reAccountMonthOrder(accountIds, startDate, endDate);
        reBrandSerial(brandId, startDate, endDate);
        reAccountMonthType(accountIds, startDate, endDate);
        //excelData(brandId, startDate + "00:00:00", endDate + "23:59:59");
    }


    public List<Integer> getAccountId() {
        Map<String, Object> params = new HashMap<>();
        params.put("type", "3");
        List<Integer> detects = new LinkedList<>();
        List<Account> accounts = accountDao.getAccountByType(params);
        if (null != accounts && accounts.size() > 0) {
            detects = accounts.stream().map(Account::getAccountId).collect(Collectors.toList());
        }
        return detects;
    }


    /**
     * 区域对账数据预统计
     */
    @Scheduled(cron = "0 0 4 * * ?")//0
    public void reAccountOrder() {
        Date nowDate = new Date();
        List<Integer> detects = getAccountId();

        long startTime = System.currentTimeMillis();
        detects.forEach(account -> {
            /**查询区域相对应的品牌*/
            Account parentAccount = accountDao.getAgentId(account);
            if (NullUtils.isEmpty(parentAccount)) {
                /**没有品牌id，就不插入这个数据*/
                return;
            }
            Integer brandId = parentAccount.getParentId();
            /**统计调度费用*/
            AccountDataDaySta accountDataDaySta = reconciliationDao.getDateByAccount(account);
            if (!NullUtils.isEmpty(accountDataDaySta)) {
                /**查看最后一天数据是否是昨天添加的*/
                if (!DateTimes.getDayAgo().equals(DateTimeUtil.DateTimeToStringYMD(accountDataDaySta.getOrderDate()))) {
                    /**获取传入时间每天的日期*/
                    LinkedList<String> findTimeList = DateTimeUtil.findDays(DateTimeUtil.DateTimeToStringYMD(accountDataDaySta.getOrderDate()), DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)));
                    /**除去开头时间和结尾时间*/
                    findTimeList.removeFirst();
                    for (String findTime : findTimeList) {
                        try {
                            /**数据赋值*/
                            reconciliationDao.addBatchAccountData(dataAccountAssignment(findTime, account, brandId, nowDate));
                        } catch (Exception e) {
                            log.error(account + "区域的" + findTime + "日期数据插入有误");
                            log.error(e.getMessage(), e);
                            continue;
                        }
                    }
                } else {
                    /**修改添加时间*/
                    accountDataDaySta.setAddTime(new Date());
                    reconciliationDao.updateDate(accountDataDaySta);
                }
            } else {
                LinkedList<String> findTimeList = new LinkedList<>();
                /**查询数据中最早的时间，遍历时间插入数据*/
                /**查询骑行支付订单记录最早的数据（天）*/
                Date rideOrderDate = rideOrderDayStaDao.getEarliestData(account);
                if (!NullUtils.isEmpty(rideOrderDate)) {
                    /**获取有数据开始的时间到现在，将所有的数据都进行预统计*/
                    findTimeList = DateTimeUtil.findDays(DateTimeUtil.DateTimeToStringYMD(rideOrderDate), DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)));
                }
                findTimeList.forEach(findTime -> {
                    try {
                        reconciliationDao.addBatchAccountData(dataAccountAssignment(findTime, account, brandId, nowDate));
                    } catch (Exception e) {
                        log.error(account + "区域的" + findTime + "日期数据插入有误");
                        log.error(e.getMessage(), e);
                        return;
                    }
                });
            }

        });
        log.info("对账数据统计耗时：" + (System.currentTimeMillis() - startTime) + "毫秒");
    }

    /**
     * 区域对账数据预统计(手动调用)
     */
    public void reAccountOrder(String accountIds, String startDate, String endDate) {
        List<Integer> detects = new ArrayList<>();
        if (!NullUtils.isEmpty(accountIds)) {
            detects = StringUtil.getIntegerList(accountIds);
        } else {
            detects = getAccountId();
        }
        Date nowDate = new Date();
        long startTime = System.currentTimeMillis();
        detects.forEach(account -> {
            /**查询区域相对应的品牌*/
            Account parentAccount = accountDao.getAgentId(account);
            Integer brandId = parentAccount.getParentId();
            /**统计调度费用*/
            LinkedList<String> findTimeList = new LinkedList<>();
            /**查询数据中最早的时间，遍历时间插入数据*/
            findTimeList = DateTimeUtil.findDays(startDate, endDate);
            findTimeList.forEach(findTime -> {
                try {
                    reconciliationDao.addBatchAccountData(dataAccountAssignment(findTime, account, brandId, nowDate));
                } catch (Exception e) {
                    log.error(account + "区域的" + findTime + "日期数据插入有误");
                    log.error(e.getMessage(), e);
                    return;
                }
            });

        });
        log.info("对账数据统计耗时：" + (System.currentTimeMillis() - startTime) + "毫秒");
    }

    /**
     * 区域对账数据的查询以及赋值
     *
     * @param findTime 查询时间
     * @param account  区域id
     * @param brandId  品牌标识
     * @param nowDate  现在日期
     * @return {@link List}<{@link AccountDataDaySta}>
     */
    public List<AccountDataDaySta> dataAccountAssignment(String findTime, Integer account, Integer brandId, Date nowDate) {
        List<AccountDataDaySta> accountDataDaySta = new LinkedList<>();

        Map<String, Object> recentlyMap = new HashMap<>();
        recentlyMap.put("accountId", account);
        recentlyMap.put("startTime", findTime);
        recentlyMap.put("endTime", DateTimeUtil.getNextDay(findTime));

        /**封装区域对账金额的数据*/
        AccountDataDaySta dataByMoney = new AccountDataDaySta(brandId, account, DateTimes.StringToDate(findTime), nowDate, 0);
        /**封装区域对账订单的数据*/
        AccountDataDaySta dataByCount = new AccountDataDaySta(brandId, account, DateTimes.StringToDate(findTime), nowDate, 1);

        /**骑行支付*/
        RideOrderDaySta rideOrderList = rideLogDao.selectDateByMap(recentlyMap);
        /**骑行支付数量*/
        dataByCount.setOrderPayMoney(rideOrderList.getOrderCount());
        /**骑行支付金额*/
        dataByMoney.setOrderPayMoney(rideOrderList.getOrderMoney());


        /**查询时间内的调度记录数据，罚款收入*/
        CommonDTO dispatchOrder = statDataDao.getDispatchByTime(recentlyMap);
        /**罚款订单数量*/
        dataByCount.setFineIncome(dispatchOrder.getNum());
        /**罚款订单金额*/
        dataByMoney.setFineIncome(dispatchOrder.getMoney());


        /**骑行订单退款*/
        CommonDTO returnBikeRefund = rideRefundLogDao.getRefundByTime(recentlyMap);
        /**充值结束订单退款数量*/
        dataByCount.setRideOrderRefund(returnBikeRefund.getNum());
        /**充值结束订单退款金额*/
        dataByMoney.setRideOrderRefund(returnBikeRefund.getMoney());


        /**骑行卡订单*/
        RideCardOrderDaySta rideCard = rideCardDao.statRideCard(recentlyMap);
        /**骑行卡数量*/
        dataByCount.setRideCard(rideCard.getOrderCount());
        /**骑行卡金额*/
        dataByMoney.setRideCard(rideCard.getOrderMoney());

        /**查询骑行卡退款记录*/
        recentlyMap.put("type", RechargeConstant.recharge_rideCard);
        CommonDTO rideCardRefund = userRefundLogDao.getRefundByTime(recentlyMap);
        /**骑行卡退款数量*/
        dataByCount.setRideCardRefund(rideCardRefund.getNum());
        /**骑行卡退款金额*/
        dataByMoney.setRideCardRefund(rideCardRefund.getMoney());


        /**免押卡订单*/
        DepositOrderDaySta deposits = memberFeeDao.statMem(recentlyMap);
        /**免押卡订单数量*/
        dataByCount.setDepositCard(deposits.getOrderCount());
        /**免押卡订单金额*/
        dataByMoney.setDepositCard(deposits.getOrderMoney());


        /**查询免押卡退款记录*/
        recentlyMap.put("type", RechargeConstant.recharge_Mem);
        CommonDTO depositRefund = userRefundLogDao.getRefundByTime(recentlyMap);
        /**免押卡退款数量*/
        dataByCount.setDepositCardRefund(depositRefund.getNum());
        /**免押卡退款金额*/
        dataByMoney.setDepositCardRefund(depositRefund.getMoney());


        /**会员卡订单*/
        VipCardOrderDaySta vips = vipCardDao.statVipLogByDay(recentlyMap);
        /**会员卡数量*/
        dataByCount.setVipCard(vips.getOrderCount());
        /**会员卡金额*/
        dataByMoney.setVipCard(vips.getOrderMoney());


        /**查询会员卡退款记录*/
        recentlyMap.put("type", RechargeConstant.recharge_vip);
        CommonDTO vipRefund = userRefundLogDao.getRefundByTime(recentlyMap);
        /**会员卡退款数量*/
        dataByCount.setVipCardRefund(vipRefund.getNum());
        /**会员卡退款金额*/
        dataByMoney.setVipCardRefund(vipRefund.getMoney());

        /**优惠券订单*/
        CommonDTO couponOrder = userMealLogDao.getDateByTime(recentlyMap);

        /**优惠券订单数量*/
        dataByCount.setCouponOrder(couponOrder.getNum());
        /**优惠券订单金额*/
        dataByMoney.setCouponOrder(couponOrder.getMoney());


        /**查询优惠券订单退款记录*/
        recentlyMap.put("type", RechargeConstant.recharge_meal);
        CommonDTO couponRefund = userRefundLogDao.getRefundByTime(recentlyMap);
        /**优惠券订单退款数量*/
        dataByCount.setCouponOrderRefund(couponRefund.getNum());
        /**优惠券订单退款金额*/
        dataByMoney.setCouponOrderRefund(couponRefund.getMoney());


        /**骑行收入=骑行支付-罚款订单（数量和金额都扣除）*/
        /**骑行收入数量*/
        dataByCount.setRideIncome(dataByCount.getOrderPayMoney() - dataByCount.getFineIncome());
        /**骑行收入金额*/
        dataByMoney.setRideIncome(dataByMoney.getOrderPayMoney() - dataByMoney.getFineIncome());

        accountDataDaySta.add(dataByMoney);
        accountDataDaySta.add(dataByCount);
        return accountDataDaySta;
    }

    /**
     * 品牌对账数据预统计
     */
    @Scheduled(cron = "0 30 4 * * ?")//0
    public void reBrandOrder() {
        Map<String, Object> params = new HashMap<>();
        params.put("type", "1");
        List<Integer> detects = new LinkedList<>();
        List<Account> accounts = accountDao.getAccountByType(params);
        if (null != accounts && accounts.size() > 0) {
            detects = accounts.stream().map(Account::getAccountId).collect(Collectors.toList());
        }

        detects.forEach(brandId -> {
            BrandDataDaySta brandDataDatSta = reconciliationDao.getBrandEarliestData(brandId);
            if (!NullUtils.isEmpty(brandDataDatSta)) {
                /**查看最后一天数据是否是昨天添加的*/
                if (!DateTimes.getDayAgo().equals(brandDataDatSta.getOrderDate())) {
                    /**获取传入时间每天的日期*/
                    LinkedList<String> findTimeList = DateTimeUtil.findDays(brandDataDatSta.getOrderDate(), DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)));
                    /**出去开头时间和结尾时间*/
                    findTimeList.removeFirst();
                    for (String findTime : findTimeList) {
                        try {
                            /**插入数据*/
                            reconciliationDao.addBatchBrandData(dataBrandAssignment(findTime, brandId));
                        } catch (Exception e) {
                            log.error(brandId + "区域的" + findTime + "日期数据插入有误");
                            log.error(e.getMessage(), e);
                            continue;
                        }
                    }
                } else {
                    /**修改添加时间*/
                    brandDataDatSta.setAddTime(new Date());
                    reconciliationDao.updateBrandData(brandDataDatSta);
                }
            } else {
                /**统计调度费用*/
                AccountDataDaySta accountDataDaySta = reconciliationDao.getEarlyDateByAccount(brandId);
                LinkedList<String> findTimeList = new LinkedList<>();
                if (!NullUtils.isEmpty(accountDataDaySta)) {
                    /**获取传入时间每天的日期*/
                    findTimeList = DateTimeUtil.findDays(DateTimeUtil.DateTimeToStringYMD(accountDataDaySta.getOrderDate()), DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)));
                }
                findTimeList.forEach(findTime -> {
                    try {
                        reconciliationDao.addBatchBrandData(dataBrandAssignment(findTime, brandId));
                    } catch (Exception e) {
                        log.error(brandId + "区域的" + findTime + "日期数据插入有误");
                        log.error(e.getMessage(), e);
                        return;
                    }
                });
            }
        });
    }

    /**
     * 品牌对账数据预统计(手动调用)
     */
    public void reBrandOrder(String accountIds, String startDate, String endDate) {
        List<Integer> detects = new LinkedList<>();
        if (!NullUtils.isEmpty(accountIds)) {
            detects = StringUtil.getIntegerList(accountIds);
        } else {
            Map<String, Object> params = new HashMap<>();
            params.put("type", "1");
            List<Account> accounts = accountDao.getAccountByType(params);
            if (null != accounts && accounts.size() > 0) {
                detects = accounts.stream().map(Account::getAccountId).collect(Collectors.toList());
            }
        }
        detects.forEach(brandId -> {
            /**获取传入时间每天的日期*/
            LinkedList<String> findTimeList = DateTimeUtil.findDays(startDate, endDate);
            for (String findTime : findTimeList) {
                try {
                    /**插入数据*/
                    reconciliationDao.addBatchBrandData(dataBrandAssignment(findTime, brandId));
                } catch (Exception e) {
                    log.error(brandId + "区域的" + findTime + "日期数据插入有误");
                    log.error(e.getMessage(), e);
                    continue;
                }
            }

        });
    }


    /**
     * 品牌对账数据的查询以及赋值
     *
     * @param findTime 查询时间
     * @param brandId  品牌标识
     */
    public List<BrandDataDaySta> dataBrandAssignment(String findTime, Integer brandId) {

        Map<String, Object> recentlyMap = new HashMap<>(5);
        recentlyMap.put("brandId", brandId);
        recentlyMap.put("startTime", findTime);
        recentlyMap.put("endTime", DateTimeUtil.getNextDay(findTime));

        BrandDataDaySta brandDataMoney = new BrandDataDaySta(brandId, findTime, 0);
        BrandDataDaySta brandDataCount = new BrandDataDaySta(brandId, findTime, 1);

        /**根据品牌id查询出区域预统计相对应的数据*/
        List<AccountDataDaySta> dataDay = reconciliationDao.getDataByBrandId(recentlyMap);


        if (!NullUtils.isEmpty(dataDay)) {
            Map<Integer, List<AccountDataDaySta>> dataDayMap = dataDay.stream().collect(Collectors.groupingBy(AccountDataDaySta::getType));
            if (!NullUtils.isEmpty(dataDayMap.get(0))) {
                AccountDataDaySta dataDayMoney = dataDayMap.get(0).get(0);
                brandDataMoney.setOrderPayMoney((int) dataDayMoney.getOrderPayMoney());
                brandDataMoney.setRideIncome((int) dataDayMoney.getRideIncome());
                BeanUtils.copyProperties(dataDayMoney, brandDataMoney);
            }
            if (!NullUtils.isEmpty(dataDayMap.get(1))) {
                AccountDataDaySta dataDayCount = dataDayMap.get(1).get(0);
                dataDayCount.setOrderPayMoney((int) dataDayCount.getOrderPayMoney());
                dataDayCount.setRideIncome((int) dataDayCount.getRideIncome());
                BeanUtils.copyProperties(dataDayCount, brandDataCount);
            }
        }
        /**根据品牌id查询出用户押金的提交和退还记录*/
        CommonDTO depositLogList = weixinDepositLogDao.getCommitBrandDeposit(recentlyMap);
        brandDataMoney.setUserCommitPledge(depositLogList.getMoney());
        brandDataCount.setUserCommitPledge(depositLogList.getNum());

        CommonDTO refundDepositLogList = weixinDepositLogDao.getRefundBrandDeposit(recentlyMap);
        brandDataMoney.setUserRefundPledge(refundDepositLogList.getMoney());
        brandDataCount.setUserRefundPledge(refundDepositLogList.getNum());


        /**根据品牌id查询出手动充值和扣款记录*/
        List<CommonDTO> manualMoney = moneyOpeLogDao.getBrandManualMoney(recentlyMap);
        if (!NullUtils.isEmpty(manualMoney)) {
            Map<Integer, List<CommonDTO>> manualMap = manualMoney.stream().collect(Collectors.groupingBy(CommonDTO::getType));
            /**如果手动扣款数据不为空*/
            if (!NullUtils.isEmpty(manualMap.get(0))) {
                brandDataMoney.setManualDeductMoney(manualMap.get(0).get(0).getMoney());
                brandDataCount.setManualDeductMoney(manualMap.get(0).get(0).getNum());
            }
            /**如果手动充值数据不为空*/
            if (!NullUtils.isEmpty(manualMap.get(1))) {
                brandDataMoney.setManualRechargeMoney(manualMap.get(1).get(0).getMoney());
                brandDataCount.setManualRechargeMoney(manualMap.get(1).get(0).getNum());
            }
        }

        /**根据品牌id查询出用户充值记录*/
        Recharge rechargeMoney = rechargeDao.getRechargeMoney(recentlyMap);
        if (!NullUtils.isEmpty(rechargeMoney)) {
            double money = rechargeMoney.getMoney();
            brandDataMoney.setRechargeMoney((int) money);
            brandDataCount.setRechargeMoney(rechargeMoney.getNum());
        }

        List<Account> accountList = accountDao.getById(brandId);
        List<Integer> accountIds = new LinkedList<>();
        if (null != accountList && accountList.size() > 0) {
            accountIds = accountList.stream().map(Account::getAccountId).collect(Collectors.toList());
            accountIds.add(brandId);
            recentlyMap.put("accountList", accountIds);
        }

        /**根据品牌id查询出用户退款记录*/
        CommonDTO rechargeRefund = userRefundLogDao.getRechargeRefundMoney(recentlyMap);
        if (!NullUtils.isEmpty(rechargeRefund)) {
            brandDataMoney.setRechargeRefund(rechargeRefund.getMoney());
            brandDataCount.setRechargeRefund(rechargeRefund.getNum());
        }

        List<BrandDataDaySta> brandDataDayStaList = new LinkedList<>();
        brandDataDayStaList.add(brandDataCount);
        brandDataDayStaList.add(brandDataMoney);

        return brandDataDayStaList;
    }

    /**
     * 区域对账数据月统计
     */
    @Scheduled(cron = "0 0 1 1 * ?")//
    public void reAccountMonthOrder() {
        List<Integer> detects = getAccountId();
        detects.forEach(account -> {
            Map<String, Object> recentlyMap = new HashMap<>();
            recentlyMap.put("accountId", account);
            /**查询月统计是否有数据*/
            AccountDataMonthSta accountDataMonthSta = reconciliationDao.getRecentlyDate(account);
            if (!NullUtils.isEmpty(accountDataMonthSta)) {
                /**查询最后一条数据时间是否是上一个月*/
                try {
                    if (!accountDataMonthSta.getOrderDate().equals(DateTimeUtil.getLastMonth(0, ""))) {
                        /**开始时间为最后数据的后一个月，结束时间为上一个月的月底*/
                        recentlyMap.put("startTime", DateTimeUtil.addDate(accountDataMonthSta.getOrderDate(), 1));
                        recentlyMap.put("endTime", DateTimeUtil.getLastMonth(1, DateTimeUtil.getLastMonth(-1, "")));
                    } else {
                        accountDataMonthSta.setAddTime(new Date());
                        reconciliationDao.updateBrandMonth(accountDataMonthSta);
                        return;
                    }
                } catch (ParseException e) {
                    log.error(e.getMessage(), e);
                }
            }
            List<AccountDataDaySta> dataDayStaList = reconciliationDao.getMonthDate(recentlyMap);
            if (!NullUtils.isEmpty(dataDayStaList)) {
                try {
                    reconciliationDao.addBatch(dataDayStaList);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    return;
                }
            }
        });
    }

    /**
     * 区域对账数据月统计(手动调用)
     */
    public void reAccountMonthOrder(String accountIds, String startDate, String endDate) {
        List<Integer> detects = getAccountId();
        if (!NullUtils.isEmpty(accountIds)) {
            detects = StringUtil.getIntegerList(accountIds);
        } else {
            detects = getAccountId();
        }
        detects.forEach(account -> {
            Map<String, Object> recentlyMap = new HashMap<>();
            recentlyMap.put("accountId", account);
            /**查询月统计是否有数据*/
            AccountDataMonthSta accountDataMonthSta = reconciliationDao.getRecentlyDate(account);
            if (!NullUtils.isEmpty(accountDataMonthSta)) {
                /**查询最后一条数据时间是否是上一个月*/
                try {
                    if (!accountDataMonthSta.getOrderDate().equals(DateTimeUtil.getLastMonth(0, ""))) {
                        /**开始时间为最后数据的后一个月，结束时间为上一个月的月底*/
                        recentlyMap.put("startTime", DateTimeUtil.addDate(accountDataMonthSta.getOrderDate(), 1));
                        recentlyMap.put("endTime", DateTimeUtil.getLastMonth(1, DateTimeUtil.getLastMonth(-1, "")));
                    } else {
                        accountDataMonthSta.setAddTime(new Date());
                        reconciliationDao.updateBrandMonth(accountDataMonthSta);
                        return;
                    }
                } catch (ParseException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (!NullUtils.isEmpty(startDate)) {
                recentlyMap.put("startTime", startDate);
                recentlyMap.put("endTime", endDate);
            }
            List<AccountDataDaySta> dataDayStaList = reconciliationDao.getMonthDate(recentlyMap);
            if (!NullUtils.isEmpty(dataDayStaList)) {
                try {
                    reconciliationDao.addBatch(dataDayStaList);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    return;
                }
            }
        });
    }

    /**
     * 品牌资金流水日预统计
     */
    @Scheduled(cron = "0 50 4 * * ?")//0
    public void reBrandSerialQuartz() {
        Date nowDate = new Date();
        Map<String, Object> params = new HashMap<>();
        params.put("type", "1");
        List<Integer> detects = new LinkedList<>();
        List<Account> accounts = accountDao.getAccountByType(params);
        if (null != accounts && accounts.size() > 0) {
            detects = accounts.stream().map(Account::getAccountId).collect(Collectors.toList());
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        detects.forEach(detect -> {
            /**查询微信的充值记录*/
            BrandSerialDaySta brandSerialDaySta = reconciliationDao.getRecentlyDateByBrand(detect);
            if (!NullUtils.isEmpty(brandSerialDaySta)) {
                /**查看最后一天数据是否是昨天添加的*/
                if (!brandSerialDaySta.getOrderDate().equals(DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)))) {
                    /**获取传入时间每天的日期*/
                    LinkedList<String> findTimeList = DateTimeUtil.findDays(simpleDateFormat.format(brandSerialDaySta.getOrderDate()), DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)));
                    findTimeList.removeFirst();
                    insertBrandSerial(detect, nowDate, findTimeList);
                }
            } else {
                String payTime = rechargeDao.getEarliestData(detect);
                if (!NullUtils.isEmpty(payTime)) {
                    LinkedList<String> findTimeList = DateTimeUtil.findDays(payTime, DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)));
                    insertBrandSerial(detect, nowDate, findTimeList);
                }
            }
        });
    }


    /**
     * 品牌资金流水日预统计(手动调用)
     */
    public void reBrandSerial(String accountIds, String startDate, String endDate) {
        Date nowDate = new Date();
        Map<String, Object> params = new HashMap<>();
        params.put("type", "1");
        List<Integer> detects = new LinkedList<>();
        List<Account> accounts = accountDao.getAccountByType(params);
        if (null != accounts && accounts.size() > 0) {
            detects = accounts.stream().map(Account::getAccountId).collect(Collectors.toList());
        }
        if (!NullUtils.isEmpty(accountIds)) {
            detects = StringUtil.getIntegerList(accountIds);
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (!NullUtils.isEmpty(accountIds)) {
            detects = StringUtil.getIntegerList(accountIds);
        }

        detects.forEach(detect -> {
            /**查询微信的充值记录*/
            BrandSerialDaySta brandSerialDaySta = reconciliationDao.getRecentlyDateByBrand(detect);
            if (!NullUtils.isEmpty(brandSerialDaySta)) {
                /**查看最后一天数据是否是昨天添加的*/
                if (!brandSerialDaySta.getOrderDate().equals(DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)))) {
                    /**获取传入时间每天的日期*/
                    LinkedList<String> findTimeList = DateTimeUtil.findDays(simpleDateFormat.format(brandSerialDaySta.getOrderDate()), DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)));
                    findTimeList.removeFirst();
                    if (!NullUtils.isEmpty(startDate)) {
                        findTimeList = DateTimeUtil.findDays(startDate, endDate);
                    }
                    insertBrandSerial(detect, nowDate, findTimeList);
                }
            } else {
                String payTime = rechargeDao.getEarliestData(detect);
                if (!NullUtils.isEmpty(payTime)) {
                    LinkedList<String> findTimeList = DateTimeUtil.findDays(payTime, DateTimeUtil.DateTimeToStringYMD(DateTimeUtil.addDay(new Date(), -1)));
                    if (!NullUtils.isEmpty(startDate)) {
                        findTimeList = DateTimeUtil.findDays(startDate, endDate);
                    }
                    insertBrandSerial(detect, nowDate, findTimeList);
                }
            }
        });
    }

    /**
     * 插入品牌流水数据
     *
     * @param detect       检测
     * @param nowDate      现在日期
     * @param findTimeList 找时间列表
     */
    public void insertBrandSerial(Integer detect, Date nowDate, LinkedList<String> findTimeList) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<Account> accountList = accountDao.getById(detect);
        List<Integer> accountIds = new LinkedList<>();
        if (null != accountList && accountList.size() > 0) {
            accountIds = accountList.stream().map(Account::getAccountId).collect(Collectors.toList());
            accountIds.add(detect);
        }
        /**获取传入时间每天的日期*/
        for (String findTime : findTimeList) {
            Map<String, Object> recentlyMap = new HashMap<>(3);
            try {
                /**统计微信的流水*/
                Date time = simpleDateFormat.parse(findTime);
                recentlyMap.put("brandId", detect);
                recentlyMap.put("accountList", accountIds);
                recentlyMap.put("startTime", findTime);
                recentlyMap.put("endTime", DateTimeUtil.getNewDate(time, 23, 59, 59));
                Date date = simpleDateFormat.parse(findTime);
                //插入微信流水数据
                List<Integer> WXTypeList = Arrays.asList(RechargeConstant.RECHARGE_WEIXIN_APP, RechargeConstant.RECHARGE_WEIXIN_XCX, RechargeConstant.RECHARGE_WEIXIN_AFF, RechargeConstant.RECHARGE_WEIXIN_ZK_XCX);
                serialInsert(recentlyMap, WXTypeList, 0, detect, date, nowDate);
                //插入支付宝流水数据
                List<Integer> ZFBTypeList = Arrays.asList(RechargeConstant.RECHARGE_ZFB_APP, RechargeConstant.RECHARGE_ZFB_XCX, RechargeConstant.RECHARGE_WEIXIN_ZK_ZFB);
                serialInsert(recentlyMap, ZFBTypeList, 1, detect, date, nowDate);
                //插入汇付流水数据
                List<Integer> AdaPayTypeList = Arrays.asList(RechargeConstant.ZH_PAY, RechargeConstant.RECHARGE_PAY_ADAPAY_ZFB);
                serialInsert(recentlyMap, AdaPayTypeList, 2, detect, date, nowDate);
            } catch (ParseException e) {
                log.error(e.getMessage(), e);
                continue;
            }
        }
    }

    /**
     * 插入流水数据
     *
     * @param recentlyMap
     * @param typeList
     * @param platformType
     * @param detect
     * @param findTime
     * @param nowDate
     */
    public void serialInsert(Map<String, Object> recentlyMap, List<Integer> typeList, Integer platformType, Integer detect, Date findTime, Date nowDate) {
        recentlyMap.put("typeList", typeList);
        BrandSerialDaySta brandSerial = null;
        /**流水流入,包含押金*/
        BrandSerialDaySta brandSerialDay = rechargeDao.groupType(recentlyMap);
        /**流水流出*/
        recentlyMap.put("platformType", platformType);
        BrandSerialDaySta brandRefundSerialDay = userRefundLogDao.groupType(recentlyMap);
        CommonDTO WXCommonDTO = weixinDepositLogDao.getRefundBrandDeposit(recentlyMap);

        Integer serialMoney = brandSerialDay.getOrderMoney();
        Integer serialCount = brandSerialDay.getOrderCount();

        Integer serialRefundMoney = brandRefundSerialDay.getOrderMoney() + WXCommonDTO.getMoney();
        Integer serialRefundCount = brandRefundSerialDay.getOrderCount() + WXCommonDTO.getNum();

        brandSerial = new BrandSerialDaySta(detect, platformType, serialCount - serialRefundCount, serialMoney - serialRefundMoney, findTime, nowDate);
        reconciliationDao.insertSerial(brandSerial);
    }

    /**
     * 区域月份数据根据时间分类
     */
    @Scheduled(cron = "0 0 1 2 * ?")//0
    public void reAccountMonthType() {
        List<Integer> detects = getAccountId();
        Map<String, Object> recentlyMap = new HashMap<>();
        detects.forEach(detect -> {
            /**查询区域相对应的品牌*/
            Account parentAccount = accountDao.getAgentId(detect);
            if (NullUtils.isEmpty(parentAccount)) {
                /**没有品牌id，就不插入这个数据*/
                return;
            }
            Integer brandId = parentAccount.getParentId();
            recentlyMap.put("accountId", detect);
            MonthDateType monthDateType = reconciliationDao.selectMonthDateType(recentlyMap);
            if (!NullUtils.isEmpty(monthDateType)) {
                try {
                    if (!monthDateType.getOperaDate().equals(DateTimeUtil.getLastMonth(0, ""))) {
                        /**开始时间为最后数据的后一个月，结束时间为上一个月的月底*/
                        recentlyMap.put("startTime", DateTimeUtil.addDate(monthDateType.getOperaDate(), 1));
                        recentlyMap.put("endTime", DateTimeUtil.getLastMonth(1, DateTimeUtil.getLastMonth(-1, "")));

                    } else {
                        monthDateType.setAddTime(new Date());
                        reconciliationDao.updateMonthDateType(monthDateType);
                        return;
                    }
                } catch (ParseException e) {
                    log.error(e.getMessage(), e);
                }
            }


            /**统计骑行订单支付金额*/
            List<MonthDateType> monthDateTypeList = rideLogDao.getGroupDate(recentlyMap);
            if (!NullUtils.isEmpty(monthDateTypeList)) {
                log.info("进入订单支付统计");
                monthDateTypeList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(monthDateTypeList);
            }

            /**统计骑行订单退款金额*/
            List<MonthDateType> rideLogTypeList = rideRefundLogDao.getRideLogRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(rideLogTypeList)) {
                rideLogTypeList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(rideLogTypeList);
            }

            /**统计骑行卡订单退款金额*/
            recentlyMap.put("type", RechargeConstant.recharge_rideCard);
            recentlyMap.put("dataType", 2);
            List<MonthDateType> rideCardRefundList = userRefundLogDao.getCardRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(rideCardRefundList)) {
                rideCardRefundList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(rideCardRefundList);
            }

            /**统计免押卡订单退款金额*/
            recentlyMap.put("dataType", 3);
            recentlyMap.put("type", RechargeConstant.recharge_Mem);
            List<MonthDateType> memCardRefundList = userRefundLogDao.getCardRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(memCardRefundList)) {
                memCardRefundList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(memCardRefundList);
            }
            /**统计会员卡订单退款金额*/
            recentlyMap.put("dataType", 4);
            recentlyMap.put("type", RechargeConstant.recharge_vip);
            List<MonthDateType> vipCardRefundList = userRefundLogDao.getCardRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(vipCardRefundList)) {
                vipCardRefundList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(vipCardRefundList);
            }
            /**统计优惠券订单退款金额*/
            recentlyMap.put("dataType", 5);
            recentlyMap.put("type", RechargeConstant.recharge_meal);
            List<MonthDateType> mealCardRefundList = userRefundLogDao.getCardRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(mealCardRefundList)) {
                mealCardRefundList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(mealCardRefundList);
            }

        });
    }

    /**
     * 区域月份数据根据时间分类(手动调用)
     */
    public void reAccountMonthType(String accountIds, String startDate, String endDate) {
        Map<String, Object> recentlyMap = new HashMap<>();
        List<Integer> detects = new ArrayList<>();
        if (!NullUtils.isEmpty(accountIds)) {
            detects = StringUtil.getIntegerList(accountIds);
        } else {
            detects = getAccountId();
        }
        detects.forEach(detect -> {
            /**查询区域相对应的品牌*/
            Account parentAccount = accountDao.getAgentId(detect);
            Integer brandId = parentAccount.getParentId();
            recentlyMap.put("accountId", detect);
            recentlyMap.put("startTime", startDate);
            recentlyMap.put("endTime", endDate);

            /**统计骑行订单支付金额*/
            List<MonthDateType> monthDateTypeList = rideLogDao.getGroupDate(recentlyMap);
            if (!NullUtils.isEmpty(monthDateTypeList)) {
                log.info("进入订单支付统计");
                monthDateTypeList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(monthDateTypeList);
            }

            /**统计骑行订单退款金额*/
            List<MonthDateType> rideLogTypeList = rideRefundLogDao.getRideLogRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(rideLogTypeList)) {
                rideLogTypeList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(rideLogTypeList);
            }

            /**统计骑行卡订单退款金额*/
            recentlyMap.put("type", RechargeConstant.recharge_rideCard);
            recentlyMap.put("dataType", 2);
            List<MonthDateType> rideCardRefundList = userRefundLogDao.getCardRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(rideCardRefundList)) {
                rideCardRefundList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(rideCardRefundList);
            }

            /**统计免押卡订单退款金额*/
            recentlyMap.put("dataType", 3);
            recentlyMap.put("type", RechargeConstant.recharge_Mem);
            List<MonthDateType> memCardRefundList = userRefundLogDao.getCardRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(memCardRefundList)) {
                memCardRefundList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(memCardRefundList);
            }
            /**统计会员卡订单退款金额*/
            recentlyMap.put("dataType", 4);
            recentlyMap.put("type", RechargeConstant.recharge_vip);
            List<MonthDateType> vipCardRefundList = userRefundLogDao.getCardRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(vipCardRefundList)) {
                vipCardRefundList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(vipCardRefundList);
            }
            /**统计优惠券订单退款金额*/
            recentlyMap.put("dataType", 5);
            recentlyMap.put("type", RechargeConstant.recharge_meal);
            List<MonthDateType> mealCardRefundList = userRefundLogDao.getCardRefundByDate(recentlyMap);
            if (!NullUtils.isEmpty(mealCardRefundList)) {
                mealCardRefundList.forEach(object -> object.setBrandId(brandId));
                reconciliationDao.insertMonthDateType(mealCardRefundList);
            }

        });
    }


    /**
     * 定时导出每月的对账详情数据，每天数据往后追加
     */
    //@Scheduled(cron = "0 0 5 * * ?")//0
    public void excelData() throws ParseException {
        //excelData2(null, null, null);
    }

    private void excelData2(String accountIdList, String startTime, String endTime) throws ParseException {
        char c = '`';
        char t = '\t';
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        Map<String, Object> params = new HashMap<>();
        params.put("type", "1");
        List<Integer> detects = new LinkedList<>();
        List<Account> accounts = accountDao.getAccountByType(params);
        if (null != accounts && accounts.size() > 0) {
            detects = accounts.stream().map(Account::getAccountId).collect(Collectors.toList());
        }
        if (!NullUtils.isEmpty(accountIdList)) {
            detects = StringUtil.getIntegerList(accountIdList);
        }
        boolean headFlag = false;
        String rideLogTitle = "区域名称\t" + "订单编号\t" + "订单金额\t" + " 手机号\t" + " 车辆编号\t" + " 设备编号\t" + " 开始时间\t" + "结束时间\t" + "里程(公里)\t" + "支付时间\t";
        String rideRefundTitle = "区域名称\t" + "订单编号\t" + "退款金额\t" + "操作时间\t" + "用户电话号码\t" + "操作人电话号码\t" + " 备注";
        String rideCardTitle = "区域名称\t" + "骑行卡名称\t" + " 购买时间\t" + "使用次数\t" + "订单编号\t" + "骑行卡金额\t" + "充值类型";
        String vipCardTitle = "区域名称\t" + "会员卡名称\t" + "订单号\t" + "购买时间\t" + "会员卡金额\t" + "用户电话号码\t" + "充值类型";
        String depositCardTitle = "区域名称\t" + "免押卡名称\t" + "订单号\t" + "购买时间\t" + "购买金额\t" + "用户电话号码\t" + "充值类型";
        String couponLogTitle = "区域名称\t" + "优惠券套餐名\t" + "购买时间\t" + "购买金额\t" + "用户电话号码";
        /**退款导出头部*/
        String refundLogTitle = "区域名称\t" + "用户手机号\t" + "用户名\t" + "退款金额\t" + "退款时间\t" + "订单号\t" + "退款订单号\t" + "备注\t" + "平台类型";
        String timePath;
        for (Integer brandId : detects) {
            List<Account> accountList = accountDao.getById(brandId);
            /**品牌*/
            Account brand = accountDao.getByAccountId(brandId);
            if (NullUtils.isEmpty(startTime) || NullUtils.isEmpty(endTime)) {
                startTime = DateTimeUtil.getYesterday() + " 00:00:00";
                endTime = DateTimeUtil.getYesterday() + " 23:59:59";
                timePath = DateTimeUtil.getCurrentMonth(0);
            } else {
                timePath = DateTimeUtil.getYYMM(startTime);
            }
            if (!NullUtils.isEmpty(accountList)) {
                List<Integer> accountIds = accountList.stream().map(Account::getAccountId).collect(Collectors.toList());
                for (Integer account : accountIds) {
                    /**区域*/
                    Account area = accountDao.getByAccountId(account);
                    String areaName = area.getName();

                    /**存放表格的路径*/
                    String filePath = OperaPswConstant.EXCEL_PATH + brand.getName() + "/" + timePath;

                    params.put("accountId", account);
                    params.put("startTime", startTime);
                    params.put("endTime", endTime);

                    List<RideLog> rideLogList = rideLogDao.selectRideLog(params);
                    List<String> rideLogDataList = new ArrayList<>();
                    if (!rideLogList.isEmpty()) {
                        for (RideLog record : rideLogList) {
                            StringBuilder sb = new StringBuilder();
                            sb.append(c).append(areaName).append(t)
                                    .append(c)
                                    .append(record.getOrderNO()).append(t)
                                    .append(record.getMoney() / 100.0).append(t)
                                    .append(c)
                                    .append(record.getPhone()).append(t)
                                    .append(c)
                                    .append(record.getMachineNO()).append(t)
                                    .append(c)
                                    .append(record.getUserCode()).append(t)
                                    .append(dateFormat(record.getStartTime(), simpleDateFormat)).append(t)
                                    .append(dateFormat(record.getEndTime(), simpleDateFormat)).append(t)
                                    .append(record.getMileage()).append(t)
                                    .append(dateFormat(record.getPayTime(), simpleDateFormat)).append(t);

                            rideLogDataList.add(sb.toString());
                        }
                    }
                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "骑行订单记录.xlsx"));
                    CSVUtil.writeToCsv(rideLogTitle, rideLogDataList, filePath + "/" + "骑行订单记录.xlsx", true, headFlag);
                    rideLogList.clear();


                    List<RideRefundLog> rideRefundList = rideRefundLogDao.excel(params);
                    List<String> rideRefundDataList = new ArrayList<>();
                    if (!rideRefundList.isEmpty()) {
                        for (RideRefundLog record : rideRefundList) {
                            StringBuilder sb = new StringBuilder();
                            sb.append(c)
                                    .append(areaName).append(t)
                                    .append(c)
                                    .append(record.getOrderNo()).append(t)
                                    .append(record.getMoney() / 100.0).append(t)
                                    .append(c)
                                    .append(dateFormat(record.getOperaTime(), simpleDateFormat)).append(t)
                                    .append(c)
                                    .append(record.getUserPhone()).append(t)
                                    .append(c)
                                    .append(record.getAccountUserPhone()).append(t)
                                    .append(c)
                                    .append(record.getOperaRemark()).append(t);
                            rideRefundDataList.add(sb.toString());
                        }
                    }
                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "骑行订单退款记录.xlsx"));
                    CSVUtil.writeToCsv(rideRefundTitle, rideRefundDataList, filePath + "/" + "骑行订单退款记录.xlsx", true, headFlag);
                    rideLogList.clear();


                    /**导出骑行卡*/
                    List<UserRcDetail> rideCardList = rideCardDao.selectData(params);
                    List<String> rideCardDataList = new ArrayList<>();
                    if (!rideCardList.isEmpty()) {
                        for (UserRcDetail record : rideCardList) {
                            StringBuilder sb = new StringBuilder();
                            sb.append(c)
                                    .append(areaName).append(t)
                                    .append(c)
                                    .append(record.getName()).append(t)
                                    .append(c)
                                    .append(dateFormat(record.getBuyTime(), simpleDateFormat)).append(t)
                                    .append(record.getUseCount()).append(t)
                                    .append(c)
                                    .append(record.getOrderNO()).append(t)
                                    .append(record.getMoney() / 100.0).append(t)
                                    .append(parseType(record.getPayType())).append(t);
                            rideCardDataList.add(sb.toString());
                        }
                    }

                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "骑行卡记录.xlsx"));
                    CSVUtil.writeToCsv(rideCardTitle, rideCardDataList, filePath + "/" + "骑行卡记录.xlsx", true, headFlag);
                    rideCardList.clear();


                    /**导出会员卡*/
                    List<UserRcDetail> vipCardList = vipCardDao.export(params);
                    List<String> vipCardDataList = new ArrayList<>();
                    if (!vipCardList.isEmpty()) {
                        for (UserRcDetail record : vipCardList) {
                            StringBuilder sb = new StringBuilder();
                            sb.append(c)
                                    .append(areaName).append(t)
                                    .append(c)
                                    .append(record.getName()).append(t)
                                    .append(c)
                                    .append(record.getOrderNO()).append(t)
                                    .append(c)
                                    .append(dateFormat(record.getBuyTime(), simpleDateFormat)).append(t)
                                    .append(record.getMoney() / 100.0).append(t)
                                    .append(c)
                                    .append(record.getPhone()).append(t)
                                    .append(parseType(record.getPayType())).append(t);
                            vipCardDataList.add(sb.toString());
                        }
                    }

                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "会员卡记录.xlsx"));
                    CSVUtil.writeToCsv(vipCardTitle, vipCardDataList, filePath + "/" + "会员卡记录.xlsx", true, headFlag);
                    vipCardList.clear();

                    /**免押卡导出*/
                    List<UserRcDetail> depositCardList = memberFeeDao.export(params);
                    List<String> depositCardDataList = new ArrayList<>();
                    if (!depositCardList.isEmpty()) {
                        for (UserRcDetail record : depositCardList) {
                            StringBuilder sb = new StringBuilder();
                            sb.append(c)
                                    .append(areaName).append(t)
                                    .append(c)
                                    .append(record.getName()).append(t)
                                    .append(c)
                                    .append(record.getOrderNO()).append(t)
                                    .append(c)
                                    .append(dateFormat(record.getBuyTime(), simpleDateFormat)).append(t)
                                    .append(record.getMoney() / 100.0).append(t)
                                    .append(c)
                                    .append(record.getPhone()).append(t)
                                    .append(parseType(record.getPayType())).append(t);
                            depositCardDataList.add(sb.toString());
                        }
                    }

                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "免押卡记录.xlsx"));
                    CSVUtil.writeToCsv(depositCardTitle, depositCardDataList, filePath + "/" + "免押卡记录.xlsx", true, headFlag);
                    depositCardList.clear();

                    /**优惠券导出*/
                    List<UserMealLog> couponLogList = userMealLogDao.excel(params);
                    List<String> couponLogDataList = new ArrayList<>();
                    if (!couponLogList.isEmpty()) {
                        for (UserMealLog record : couponLogList) {
                            CouponMeal couponMeal = couponMealDao.selectCouponMealById(record.getMealId());
                            if (NullUtils.isEmpty(couponMeal)) {
                                continue;
                            }
                            StringBuilder sb = new StringBuilder();
                            sb.append(c)
                                    .append(areaName).append(t)
                                    .append(c)
                                    .append(couponMeal.getName()).append(t)
                                    .append(c)
                                    .append(dateFormat(record.getAddTime(), simpleDateFormat)).append(t)
                                    .append(record.getPrice() / 100.0).append(t)
                                    .append(c)
                                    .append(record.getPhone()).append(t);
                            couponLogDataList.add(sb.toString());
                        }
                    }

                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "优惠券记录.xlsx"));
                    CSVUtil.writeToCsv(couponLogTitle, couponLogDataList, filePath + "/" + "优惠券记录.xlsx", true, headFlag);
                    depositCardList.clear();


                    /**查询骑行卡退款记录*/
                    params.put("refundType", RechargeConstant.recharge_rideCard);
                    List<UserRefundLog> rideCardRefundLogList = userRefundLogDao.excelRefundLog(params);
                    List<String> refundLogDataList = new ArrayList<>();
                    if (!rideCardRefundLogList.isEmpty()) {
                        for (UserRefundLog record : rideCardRefundLogList) {
                            User user = userDao.selectByUserId(record.getUserId());
                            if (NullUtils.isEmpty(user)) {
                                user.setName("此人不存在");
                                user.setPhone("");
                            }
                            StringBuilder sb = new StringBuilder();
                            sb.append(c)
                                    .append(areaName).append(t)
                                    .append(c)
                                    .append(user.getPhone()).append(t)
                                    .append(c)
                                    .append(user.getName()).append(t)
                                    .append(record.getReturnMoney() / 100.0).append(t)
                                    .append(c)
                                    .append(dateFormat(record.getReturnTime(), simpleDateFormat)).append(t)
                                    .append(c)
                                    .append(record.getOrderNO()).append(t)
                                    .append(c)
                                    .append(record.getReturnOrderNO()).append(t)
                                    .append(c)
                                    .append(record.getRemark()).append(t)
                                    .append(parsePlatformType(record.getPlatformType()));
                            refundLogDataList.add(sb.toString());
                        }
                    }

                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "骑行卡退款记录.xlsx"));
                    CSVUtil.writeToCsv(refundLogTitle, refundLogDataList, filePath + "/" + "骑行卡退款记录.xlsx", true, headFlag);
                    rideCardRefundLogList.clear();

                    /**查询会员卡退款记录*/
                    params.put("refundType", RechargeConstant.recharge_vip);
                    List<UserRefundLog> vipCardRefundLogList = userRefundLogDao.excelRefundLog(params);
                    List<String> vipRefundLogDataList = new ArrayList<>();
                    if (!vipCardRefundLogList.isEmpty()) {
                        for (UserRefundLog record : vipCardRefundLogList) {
                            User user = userDao.selectByUserId(record.getUserId());
                            if (NullUtils.isEmpty(user)) {
                                user.setName("此人不存在");
                                user.setPhone("");
                            }
                            StringBuilder sb = new StringBuilder();
                            sb.append(c).append(areaName).append(t)
                                    .append(c)
                                    .append(user.getPhone()).append(t)
                                    .append(c)
                                    .append(user.getName()).append(t)
                                    .append(record.getReturnMoney() / 100.0).append(t)
                                    .append(c)
                                    .append(dateFormat(record.getReturnTime(), simpleDateFormat)).append(t)
                                    .append(c)
                                    .append(record.getOrderNO()).append(t)
                                    .append(c)
                                    .append(record.getReturnOrderNO()).append(t)
                                    .append(c)
                                    .append(record.getRemark()).append(t)
                                    .append(parsePlatformType(record.getPlatformType()));
                            vipRefundLogDataList.add(sb.toString());
                        }
                    }

                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "会员卡退款记录.xlsx"));
                    CSVUtil.writeToCsv(refundLogTitle, vipRefundLogDataList, filePath + "/" + "会员卡退款记录.xlsx", true, headFlag);
                    vipCardRefundLogList.clear();


                    /**导出免押卡退款记录*/
                    params.put("refundType", RechargeConstant.recharge_Mem);
                    List<UserRefundLog> depositCardRefundLogList = userRefundLogDao.excelRefundLog(params);
                    List<String> depositCardRefundLogDataList = new ArrayList<>();
                    if (!depositCardRefundLogList.isEmpty()) {
                        for (UserRefundLog record : depositCardRefundLogList) {
                            User user = userDao.selectByUserId(record.getUserId());
                            if (NullUtils.isEmpty(user)) {
                                user.setName("此人不存在");
                                user.setPhone("");
                            }
                            StringBuilder sb = new StringBuilder();
                            sb.append(c).append(areaName).append(t)
                                    .append(c)
                                    .append(user.getPhone()).append(t)
                                    .append(c)
                                    .append(user.getName()).append(t)
                                    .append(record.getReturnMoney() / 100.0).append(t)
                                    .append(c)
                                    .append(dateFormat(record.getReturnTime(), simpleDateFormat)).append(t)
                                    .append(c)
                                    .append(record.getOrderNO()).append(t)
                                    .append(c)
                                    .append(record.getReturnOrderNO()).append(t)
                                    .append(c)
                                    .append(record.getRemark()).append(t)
                                    .append(parsePlatformType(record.getPlatformType()));
                            depositCardRefundLogDataList.add(sb.toString());
                        }
                    }

                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "免押卡退款记录.xlsx"));
                    CSVUtil.writeToCsv(refundLogTitle, depositCardRefundLogDataList, filePath + "/" + "免押卡退款记录.xlsx", true, headFlag);
                    rideCardRefundLogList.clear();


                    /**查询优惠券退款记录*/
                    params.put("refundType", RechargeConstant.recharge_meal);
                    List<UserRefundLog> couponRefundLogList = userRefundLogDao.excelRefundLog(params);
                    List<String> couponDataList = new ArrayList<>();
                    if (!couponRefundLogList.isEmpty()) {
                        for (UserRefundLog record : couponRefundLogList) {
                            User user = userDao.selectByUserId(record.getUserId());
                            if (NullUtils.isEmpty(user)) {
                                user.setName("此人不存在");
                                user.setPhone("");
                            }
                            StringBuilder sb = new StringBuilder();
                            sb.append(c).append(areaName).append(t)
                                    .append(c)
                                    .append(user.getPhone()).append(t)
                                    .append(c)
                                    .append(user.getName()).append(t)
                                    .append(record.getReturnMoney() / 100.0).append(t)
                                    .append(c)
                                    .append(dateFormat(record.getReturnTime(), simpleDateFormat)).append(t)
                                    .append(c)
                                    .append(record.getOrderNO()).append(t)
                                    .append(c)
                                    .append(record.getReturnOrderNO()).append(t)
                                    .append(c)
                                    .append(record.getRemark()).append(t)
                                    .append(parsePlatformType(record.getPlatformType()));
                            couponDataList.add(sb.toString());
                        }
                    }

                    headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(filePath + "/" + "优惠券退款记录.xlsx"));
                    CSVUtil.writeToCsv(refundLogTitle, couponDataList, filePath + "/" + "优惠券退款记录.xlsx", true, headFlag);
                    rideCardRefundLogList.clear();
                }
            }

            String brandFilePath = OperaPswConstant.EXCEL_PATH + brand.getName() + "/" + timePath;

            params.put("accountId", brandId);

            /**导出押金记录*/
            List<WeixinDepositLog> depositLogList = weixinDepositLogDao.export(params);
            List<String> rideLogDataList = new ArrayList<>();
            String userPledgeTitle = "手机号\t" + "押金金额\t" + " 商户平台订单号\t" + " 是否已退还\t" + " 退还时间\t" + " 退款订单号";
            if (!depositLogList.isEmpty()) {
                for (WeixinDepositLog record : depositLogList) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(c)
                            .append(record.getPhone()).append(t)
                            .append(record.getDepositMoney() / 100.0).append(t)
                            .append(c)
                            .append(record.getOut_trade_no()).append(t)
                            .append(record.getIsReturn() ? "是" : "否").append(t)
                            .append(dateFormat(record.getReturnTime(), simpleDateFormat)).append(t)
                            .append(c)
                            .append(record.getOut_refund_no()).append(t);
                    rideLogDataList.add(sb.toString());
                }
            }

            headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(brandFilePath + "/" + "押金记录.xlsx"));
            CSVUtil.writeToCsv(userPledgeTitle, rideLogDataList, brandFilePath + "/" + "押金记录.xlsx", true, headFlag);
            depositLogList.clear();

            List<Integer> areas = Arrays.asList(brandId);
            List<ExportMoneyOpeLog> manualLogList = moneyOpeLogDao.export(new MoneyOpeLog(simpleDateFormat.parse(startTime), simpleDateFormat.parse(endTime), areas));
            List<String> manualLogDataList = new ArrayList<>();
            String manualLogTitle = "用户手机号\t" + "操作人手机号\t" + "资金类型\t" + "变动类型\t" + "金额\t" + "操作时间\t" + "备注";
            if (!manualLogList.isEmpty()) {
                for (ExportMoneyOpeLog record : manualLogList) {
                    if (null != record.getAccountUserId()) {
                        int accountUserId = Integer.parseInt(record.getAccountUserId());
                        AccountUser accountUser = accountUserDao.getAccountUserById(accountUserId);
                        if (null != accountUser) {
                            record.setAccountUserId(accountUser.getName());
                        } else {
                            record.setAccountUserId(null);
                        }
                    }
                    if (null != record.getUserId()) {
                        int userId = Integer.parseInt(record.getUserId());
                        User user = userDao.getByUserId(userId);
                        if (null != user) {
                            record.setUserId(user.getName());
                        } else {
                            record.setUserId(null);
                        }

                    }
                    record.setMoneyType("1".equals(record.getMoneyType()) ? "个人余额" : "礼品卡余额");
                    record.setChangeType("1".equals(record.getChangeType()) ? "充值" : "扣款");

                    StringBuilder sb = new StringBuilder();
                    sb.append(c)
                            .append(record.getUserPhone()).append(t)
                            .append(c)
                            .append(record.getAccountUserPhone()).append(t)
                            .append(c)
                            .append(record.getMoneyType()).append(t)
                            .append(c)
                            .append(record.getChangeType()).append(t)
                            .append(Double.parseDouble(record.getMoney())).append(t)
                            .append(dateFormat(record.getOperaTime(), simpleDateFormat)).append("\t")
                            .append(c)
                            .append(record.getOperaRemark()).append(t);
                    manualLogDataList.add(sb.toString());
                }
            }

            headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(brandFilePath + "/" + "手工操作资金记录.xlsx"));
            CSVUtil.writeToCsv(manualLogTitle, manualLogDataList, brandFilePath + "/" + "手工操作资金记录.xlsx", true, headFlag);
            manualLogList.clear();

            List<Recharge> rechargeList = rechargeDao.exportBalance(params);
            List<String> rechargeDataList = new ArrayList<>();
            String rechargeTitle = "订单编号\t" + "手机号\t" + "充值金额(元)\t" + "充值时间\t" + "支付时间\t" + "是否是押金\t" + "备注\t" + "平台类型";
            if (!rechargeList.isEmpty()) {
                for (Recharge record : rechargeList) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(c)
                            .append(record.getOrderNO()).append(t)
                            .append(c)
                            .append(record.getPhone()).append(t)
                            .append(record.getMoney() / 100.0).append(t)
                            .append(c)
                            .append(dateFormat(record.getRechargeTime(), simpleDateFormat)).append(t)
                            .append(c)
                            .append(dateFormat(record.getPayTime(), simpleDateFormat)).append(t)
                            .append(record.getDeposit() ? "是" : "不是").append(t)
                            .append(c)
                            .append(record.getRemark()).append(t)
                            .append(parseType(record.getType()));
                    rechargeDataList.add(sb.toString());
                }
            }

            headFlag = !NullUtils.isEmpty(CSVUtil.readFromCsv(brandFilePath + "/" + "充值记录.xlsx"));
            CSVUtil.writeToCsv(rechargeTitle, rechargeDataList, brandFilePath + "/" + "充值记录.xlsx", true, headFlag);
            depositLogList.clear();

        }
    }

    /**
     * 定时导出每月的对账详情数据，每天数据往后追加
     */
    public void excelData(String accountIdList, String startTime, String endTime) throws ParseException {
        excelData2(accountIdList, startTime, endTime);
    }

    public String dateFormat(Date date, SimpleDateFormat simpleDateFormat) {
        return !NullUtils.isEmpty(date) ? "`" + simpleDateFormat.format(date) : "";
    }

    public String dateFormat(String date, SimpleDateFormat simpleDateFormat) {
        String format = "";
        if (date == null || "".equals(date)) {
            return format;
        }
        try {
            format = simpleDateFormat.format(new Date(date));
        } catch (Exception e) {
            log.error("时间格式化失败！");
        }
        return format;
    }

    /**
     * 充值类型解析
     *
     * @param rechargeType
     * @return
     */
    public String parseType(Integer rechargeType) {
        switch (rechargeType) {
            case 1:
                return "微信app";
            case 2:
                return "微信小程序";
            case 3:
                return "支付宝app";
            case 4:
                return "微信支付分";
            case 5:
                return "支付宝小程序";
            case 6:
                return "海外app支付";
            case 7:
                return "汇付微信支付";
            case 8:
                return "汇付支付宝支付";
            case 9:
                return "中科微信小程序支付";
            case 10:
                return "中科支付宝小程序支付";
            default:
                return "";
        }
    }

    /**
     * 支付平台类型解析
     *
     * @param platformType
     * @return
     */
    public String parsePlatformType(Integer platformType) {
        switch (platformType) {
            case 0:
                return "微信";
            case 1:
                return "支付宝";
            case 2:
                return "汇付平台";
            default:
                return "";
        }
    }

}

